package com.vancouver.knows.ui.activity.userpost;

import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.PictureDrawable;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.alibaba.fastjson.JSON;
import com.pangu.AMApplication;
import com.pangu.service.ActionException;
import com.pangu.task.mark.ATaskMark;
import com.pangu.ui.browser.PullListItemBrowser;
import com.pangu.ui.refresh.ARefreshViewController;
import com.pangu.util.StringUtil;
import com.squareup.picasso.Picasso;
import com.vancouver.knows.MainApplication;
import com.vancouver.knows.R;
import com.vancouver.knows.business.BSharedPrefManager;
import com.vancouver.knows.business.BusinessModule;
import com.vancouver.knows.business.bean.CategoryInfo;
import com.vancouver.knows.business.bean.FilterArgs;
import com.vancouver.knows.business.bean.UserInfo;
import com.vancouver.knows.business.bean.UserPostInfo;
import com.vancouver.knows.business.task.mark.FetchUserPostsTaskMark;
import com.vancouver.knows.business.task.mark.UserDeleteFollowTaskMark;
import com.vancouver.knows.business.task.mark.UserFollowTaskMark;
import com.vancouver.knows.ui.activity.citynews.CityNewsCommentsActivity;
import com.vancouver.knows.ui.activity.login.LoginActivity;
import com.vancouver.knows.util.AppUtils;
import com.vancouver.knows.util.CircleTransform;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Chris Li on 2016-07-13.
 */
public class UserPostListView extends PullListItemBrowser<AMApplication> {

    private Context mContext;
    private BusinessModule bModule;
    private LinearLayout mHeaderView;

    public OnUserPostRequestListener userPostRequestListener;

    public UserPostListView(Context context, ARefreshViewController mController) {
        super(context, mController);
        this.mContext = context;
        this.bModule = ((MainApplication) imContext).getBusinessModule();
    }

    @Override
    protected View createLoadingView(Context context) {
        RelativeLayout loadingView = (RelativeLayout) super.createLoadingView(context);
        LayoutParams linearLayoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        ImageView loadingImageView = new ImageView(context);
        loadingImageView.setLayoutParams(linearLayoutParams);
        loadingImageView.setImageResource(R.drawable.loading_classifieds);
        loadingImageView.setScaleType(ImageView.ScaleType.FIT_XY);
        loadingView.addView(loadingImageView, 0);
        return loadingView;
    }

    @Override
    protected BaseAdapter createAdapter() {
        return new UserPostAdapter(mContext);
    }

    @Override
    protected void addListHeader(ListView listView) {
        super.addListHeader(listView);

        mHeaderView = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.top_categories_layout, null);
        listView.addHeaderView(mHeaderView);
    }

    @Override
    protected void setListViewParameters(ListView listView) {
        super.setListViewParameters(listView);
//        listView.setDivider(new ColorDrawable(getResources().getColor(R.color.common_bg)));
//        listView.setDividerHeight(20);
        listView.setDivider(new ColorDrawable(getResources().getColor(R.color.list_item_divider_bg)));
        listView.setDividerHeight(1);
    }

    @Override
    protected void handleLoadNewItems(ATaskMark taskMark) {
        FetchUserPostsTaskMark fetchUserPostsTaskMark = (FetchUserPostsTaskMark) taskMark;
        String userId = "";
        UserInfo userInfo = bModule.getCacheManager().getUserInfo();
        if (userInfo != null) {
            userId = userInfo.getUserID();
        }
        bModule.getServiceWrapper().fetchUserPosts(this, fetchUserPostsTaskMark, userId);
    }

    public void setTaskMark(ATaskMark m) {
        mTaskMark = m;
    }

    public void setSelectedTopCategory(FetchUserPostsTaskMark fetchUserPostsTaskMark) {
        String filterString = fetchUserPostsTaskMark.getFilter();
        if (!StringUtil.isEmptyString(filterString)) {
            FilterArgs filterArgs = JSON.parseObject(filterString, FilterArgs.class);
            List<CategoryInfo> topCategories = bModule.getCacheManager().getUserPostTopCategories();
            if (filterArgs != null && topCategories != null) {
                List<FilterArgs.Category> filterCategories = filterArgs.getCategories();
                if (filterCategories.isEmpty() || filterCategories.size() > 1) {
                    setSelectedCategory(-1);
                } else {
                    String selectedFilter = filterCategories.get(0).getCategory();
                    for (int i = 0; i < topCategories.size(); i++) {
                        if (topCategories.get(i).getSlug().equals(selectedFilter)) {
                            setSelectedCategory(i);
                            break;
                        }
                    }
                }
            } else {
                setSelectedCategory(-1);
            }
        } else {
            setSelectedCategory(-1);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

    }

    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
        return false;
    }

    public interface OnFilterSelectedListener {
        void onFilterSelected(FilterArgs filterArgs);
    }

    public interface OnUserPostRequestListener {
        void onUserPostRequestFinish();
    }

    @Override
    public void receiveResult(ATaskMark taskMark, ActionException exception, Object trackerResult) {
        super.receiveResult(taskMark, exception, trackerResult);
        if (exception != null) {
            if (taskMark instanceof UserFollowTaskMark) { // follow failed, reset value
                UserFollowTaskMark userFollowTaskMark = (UserFollowTaskMark) taskMark;
                UserPostInfo userPostInfo = bModule.getCacheManager().getUserPostsInfoCache().getItemInfoById(userFollowTaskMark.getPostId());
                userPostInfo.decrementFollowCount();
                userPostInfo.setUserFollowed("N");
                notifyDataSetChanged();
            } else if (taskMark instanceof UserDeleteFollowTaskMark) { // unfollow failed, reset value
                UserDeleteFollowTaskMark userDeleteFollowTaskMark = (UserDeleteFollowTaskMark) taskMark;
                UserPostInfo userPostInfo = bModule.getCacheManager().getUserPostsInfoCache().getItemInfoById(userDeleteFollowTaskMark.getPostId());
                userPostInfo.incrementFollowCount();
                userPostInfo.setUserFollowed("Y");
                notifyDataSetChanged();
            } else if (taskMark instanceof FetchUserPostsTaskMark) {
                setCustomErrorStatusText(exception.getExMessage());
                scrollUp();
            }
        }
        if (null != userPostRequestListener){
            userPostRequestListener.onUserPostRequestFinish();
        }
    }

    @Override
    public void notifyDataSetChanged() {
        updateHeaderView();
        super.notifyDataSetChanged();
    }

    public void clearItems() {
        try {
            bModule.getCacheManager().getUserPostsInfoCache().clearCache();
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }

    private void updateHeaderView() {
        List<CategoryInfo> topCategories = bModule.getCacheManager().getUserPostTopCategories();

        if (mHeaderView == null) {
            return;
        }

        if (topCategories.size() > 0) {
            final CategoryInfo categoryInfo = topCategories.get(0);
            ImageView image = (ImageView) mHeaderView.findViewById(R.id.first_category_image);
            TextView title = (TextView) mHeaderView.findViewById(R.id.first_category_title);
            Picasso.with(mContext)
                    .load(categoryInfo.getImageUrl())
                    .fit()
                    .centerCrop()
                    .into(image);
            title.setText(categoryInfo.getName());
            mHeaderView.findViewById(R.id.first_category).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((UserPostActivity) mContext).onTopCategoryFilterSelected(categoryInfo.getSlug());
                }
            });
        }

        if (topCategories.size() > 1) {
            final CategoryInfo categoryInfo = topCategories.get(1);
            ImageView image = (ImageView) mHeaderView.findViewById(R.id.second_category_image);
            TextView title = (TextView) mHeaderView.findViewById(R.id.second_category_title);
            Picasso.with(mContext)
                    .load(categoryInfo.getImageUrl())
                    .fit()
                    .centerCrop()
                    .into(image);
            title.setText(categoryInfo.getName());
            mHeaderView.findViewById(R.id.second_category).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((UserPostActivity) mContext).onTopCategoryFilterSelected(categoryInfo.getSlug());
                }
            });
        }

        if (topCategories.size() > 2) {
            final CategoryInfo categoryInfo = topCategories.get(2);
            ImageView image = (ImageView) mHeaderView.findViewById(R.id.third_category_icon);
            TextView title = (TextView) mHeaderView.findViewById(R.id.third_category_title);
            Picasso.with(mContext)
                    .load(categoryInfo.getImageUrl())
                    .fit()
                    .centerCrop()
                    .into(image);
            title.setText(categoryInfo.getName());
            mHeaderView.findViewById(R.id.third_category).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((UserPostActivity) mContext).onTopCategoryFilterSelected(categoryInfo.getSlug());
                }
            });
        }

        mHeaderView.findViewById(R.id.fourth_category).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ((UserPostActivity) mContext).onTopCategoryFilterSelected(null);
            }
        });
    }

    private void setSelectedCategory(int position) {
        if (mHeaderView == null) {
            return;
        }

        LinearLayout categoryOne = (LinearLayout) mHeaderView.findViewById(R.id.first_category);
        LinearLayout categoryTwo = (LinearLayout) mHeaderView.findViewById(R.id.second_category);
        LinearLayout categoryThree = (LinearLayout) mHeaderView.findViewById(R.id.third_category);
        LinearLayout categoryFour = (LinearLayout) mHeaderView.findViewById(R.id.fourth_category);

        View selectMaskOne = (View) mHeaderView.findViewById(R.id.first_category_select_indicator);
        View selectMaskTwo = (View) mHeaderView.findViewById(R.id.second_category_select_indicator);
        View selectMaskThree = (View) mHeaderView.findViewById(R.id.third_category_select_indicator);

        switch (position) {
            case 0:
//                categoryOne.setBackgroundResource(R.drawable.border_background); 描边
                categoryOne.setBackgroundResource(0);
                categoryTwo.setBackgroundResource(0);
                categoryThree.setBackgroundResource(0);
                categoryFour.setBackgroundResource(0);

                selectMaskOne.setVisibility(View.VISIBLE);
                selectMaskTwo.setVisibility(View.INVISIBLE);
                selectMaskThree.setVisibility(View.INVISIBLE);
                break;

            case 1:
                categoryOne.setBackgroundResource(0);
//                categoryTwo.setBackgroundResource(R.drawable.border_background); 描边
                categoryTwo.setBackgroundResource(0);
                categoryThree.setBackgroundResource(0);
                categoryFour.setBackgroundResource(0);

                selectMaskOne.setVisibility(View.INVISIBLE);
                selectMaskTwo.setVisibility(View.VISIBLE);
                selectMaskThree.setVisibility(View.INVISIBLE);
                break;

            case 2:
                categoryOne.setBackgroundResource(0);
                categoryTwo.setBackgroundResource(0);
//                categoryThree.setBackgroundResource(R.drawable.border_background); 描边
                categoryThree.setBackgroundResource(0);
                categoryFour.setBackgroundResource(0);

                selectMaskOne.setVisibility(View.INVISIBLE);
                selectMaskTwo.setVisibility(View.INVISIBLE);
                selectMaskThree.setVisibility(View.VISIBLE);
                break;

            default:
                categoryOne.setBackgroundResource(0);
                categoryTwo.setBackgroundResource(0);
                categoryThree.setBackgroundResource(0);
                categoryFour.setBackgroundResource(0);

                selectMaskOne.setVisibility(View.INVISIBLE);
                selectMaskTwo.setVisibility(View.INVISIBLE);
                selectMaskThree.setVisibility(View.INVISIBLE);
                break;
        }
    }

    public class UserPostAdapter extends BaseAdapter {

        private LayoutInflater mLayoutInflater;
        private OnFilterSelectedListener mListener;
        private String mUserId = null;

        public UserPostAdapter(Context context) {
            this.mLayoutInflater = LayoutInflater.from(context);

            if (context instanceof OnFilterSelectedListener) {
                this.mListener = (OnFilterSelectedListener) context;
            }

            mUserId = ((BSharedPrefManager) imContext.getSharedPrefManager()).getUserId();
        }

        @Override
        public int getCount() {
            return bModule.getCacheManager().getUserPostsInfoCache().getItemInfoCount(mTaskMark);
        }

        @Override
        public Object getItem(int position) {
            return bModule.getCacheManager().getUserPostsInfoCache().getItemInfoByTypeIndex(mTaskMark, position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            final ViewHolder viewHolder;
            View view = convertView;
            if (position == getCount() - 1) {
                tryQueryNewItems(true, ATaskMark.TYPE_DEFAULT);
            }
            if (view == null) {
                view = mLayoutInflater.inflate(R.layout.user_post_item, parent, false);
                viewHolder = new ViewHolder(view);
                view.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) view.getTag();
            }

            final UserPostInfo userPostInfo = (UserPostInfo) getItem(position);

            Picasso.with(getContext()).load(userPostInfo.getAuthorAvatar()).transform(new CircleTransform()).fit().centerCrop().into(viewHolder.authorAvatar);
            viewHolder.authorAvatar.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, ProfileActivity.class);
                    intent.putExtra(ProfileActivity.USER_ID_EXTRA, userPostInfo.getAuthorId());
                    mContext.startActivity(intent);
                }
            });

            viewHolder.author.setText(userPostInfo.getPostAuthor());
            viewHolder.summary.setText(Html.fromHtml(userPostInfo.getPostContentSummary()));
            viewHolder.date.setText(mContext.getString(R.string.date_text, AppUtils.getDateStr(getContext(), userPostInfo.getPdg())));

            if (userPostInfo.getCategories().size() > 0) {
                viewHolder.category.setText(userPostInfo.getCategories().get(0).getName());
                viewHolder.category.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mListener != null) {
                            FilterArgs filterArgs = new FilterArgs();
                            List<FilterArgs.Category> categories = new ArrayList<FilterArgs.Category>();
                            categories.add(new FilterArgs.Category(userPostInfo.getCategories().get(0).getSlug(), null));
                            filterArgs.setCategories(categories);
                            mListener.onFilterSelected(filterArgs);
                        }
                    }
                });
            }

            if (userPostInfo.getSubcategories().size() > 0) {
                viewHolder.subcategory.setText(" > " + userPostInfo.getSubcategories().get(0).getName());
                viewHolder.subcategory.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mListener != null) {
                            FilterArgs filterArgs = new FilterArgs();
                            List<FilterArgs.Category> categories = new ArrayList<FilterArgs.Category>();
                            Set<String> subcategories = new TreeSet<String>();
                            subcategories.add(userPostInfo.getSubcategories().get(0).getSlug());
                            categories.add(new FilterArgs.Category(userPostInfo.getCategories().get(0).getSlug(), subcategories));
                            filterArgs.setCategories(categories);
                            mListener.onFilterSelected(filterArgs);
                        }
                    }
                });
            }

            List<String> attachedImages = userPostInfo.getPostImages();
            if (attachedImages.size() > 0) {
                viewHolder.firstImage.setVisibility(VISIBLE);
                Picasso.with(getContext()).load(attachedImages.get(0)).fit().centerCrop().into(viewHolder.firstImage);

                if (attachedImages.size() > 1) {
                    viewHolder.secondImage.setVisibility(VISIBLE);
                    Picasso.with(getContext()).load(attachedImages.get(1)).fit().centerCrop().into(viewHolder.secondImage);
                } else {
                    viewHolder.secondImage.setVisibility(GONE);
                }

                if (attachedImages.size() > 2) {
                    viewHolder.thirdImage.setVisibility(VISIBLE);
                    Picasso.with(getContext()).load(attachedImages.get(2)).fit().centerCrop().into(viewHolder.thirdImage);
                } else {
                    viewHolder.thirdImage.setVisibility(GONE);
                }

                if (attachedImages.size() > 3) {
                    viewHolder.fourthImage.setVisibility(VISIBLE);
                    Picasso.with(getContext()).load(attachedImages.get(3)).fit().centerCrop().into(viewHolder.fourthImage);
                    viewHolder.moreImagesText.setText(attachedImages.size() - 3 + "+");
                    viewHolder.moreImagesText.setVisibility(VISIBLE);
                } else {
                    viewHolder.fourthImage.setVisibility(GONE);
                    viewHolder.moreImagesText.setVisibility(GONE);
                }

            } else {
                viewHolder.firstImage.setVisibility(GONE);
                viewHolder.secondImage.setVisibility(GONE);
                viewHolder.thirdImage.setVisibility(GONE);
                viewHolder.fourthImage.setVisibility(GONE);
                viewHolder.moreImagesText.setVisibility(GONE);
            }

            try {
                if (Integer.valueOf(userPostInfo.getFollowCount()) > 0) {
                    viewHolder.followCount.setText(userPostInfo.getFollowCount());
                } else {
                    viewHolder.followCount.setText(R.string.follow);
                }
            } catch (NumberFormatException e) {
                viewHolder.followCount.setText(R.string.follow);
            }

            viewHolder.followButton.setOnCheckedChangeListener(null);
            if (userPostInfo.getUserFollowed() == null || userPostInfo.getUserFollowed().equals("N")) {
                viewHolder.followButton.setChecked(false);
            } else if (userPostInfo.getUserFollowed().equals("Y")) {
                viewHolder.followButton.setChecked(true);
            }

            if (mUserId == null) {
                viewHolder.followButton.setOnCheckedChangeListener(null);
                viewHolder.followButton.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        boolean isChecked = viewHolder.followButton.isChecked();
                        viewHolder.followButton.setChecked(!isChecked);
                        mContext.startActivity(new Intent(mContext, LoginActivity.class));
                    }
                });
            } else {
                viewHolder.followButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                        if (isChecked) {
                            userPostInfo.incrementFollowCount();
                            viewHolder.followCount.setText(userPostInfo.getFollowCount());
                            userPostInfo.setUserFollowed("Y");
                            UserFollowTaskMark userFollowTaskMark = bModule.getTaskMarkPool().getUserFollowTaskMark(userPostInfo.getId());
                            bModule.getServiceWrapper().userFollow(UserPostListView.this, userFollowTaskMark, userPostInfo.getId(), mUserId);
                        } else {
                            userPostInfo.decrementFollowCount();
                            if (Integer.valueOf(userPostInfo.getFollowCount()) > 0) {
                                viewHolder.followCount.setText(userPostInfo.getFollowCount());
                            } else {
                                viewHolder.followCount.setText(R.string.follow);
                            }
                            userPostInfo.setUserFollowed("N");
                            UserDeleteFollowTaskMark userDeleteFollowTaskMark = bModule.getTaskMarkPool().getUserDeleteFollowTaskMark(userPostInfo.getId());
                            bModule.getServiceWrapper().userDeleteFollow(UserPostListView.this, userDeleteFollowTaskMark, userPostInfo.getId(), mUserId);
                        }
                    }
                });
            }

            try {
                if (userPostInfo.getCommentCount() > 0) {
                    viewHolder.commentCount.setText(String.valueOf(userPostInfo.getCommentCount()));
                } else {
                    viewHolder.commentCount.setText(R.string.comment);
                }
            } catch (NumberFormatException e) {
                viewHolder.commentCount.setText(R.string.comment);
            }
            viewHolder.commentIcon.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, CityNewsCommentsActivity.class);
                    intent.putExtra("postId", userPostInfo.getId());
                    ((UserPostActivity) mContext).startActivityForResult(intent, CityNewsCommentsActivity.NEW_COMMENT_REQUEST);
                }
            });
            viewHolder.commentCount.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, CityNewsCommentsActivity.class);
                    intent.putExtra("postId", userPostInfo.getId());
                    ((UserPostActivity) mContext).startActivityForResult(intent, CityNewsCommentsActivity.NEW_COMMENT_REQUEST);
                }
            });

            view.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(mContext, UserPostDetailActivity.class);
                    intent.putExtra(UserPostDetailActivity.POST_ID_EXTRA, userPostInfo.getId());
                    mContext.startActivity(intent);
                }
            });

            return view;
        }

        public class ViewHolder {
            @Bind(R.id.author)
            TextView author;
            @Bind(R.id.author_avatar)
            ImageView authorAvatar;
            @Bind(R.id.date)
            TextView date;
            @Bind(R.id.summary)
            TextView summary;
            @Bind(R.id.category)
            TextView category;
            @Bind(R.id.subcategory)
            TextView subcategory;
            @Bind(R.id.first_image)
            ImageView firstImage;
            @Bind(R.id.second_image)
            ImageView secondImage;
            @Bind(R.id.third_image)
            ImageView thirdImage;
            @Bind(R.id.fourth_image)
            ImageView fourthImage;
            @Bind(R.id.follow_count)
            TextView followCount;
            @Bind(R.id.comment_icon)
            ImageView commentIcon;
            @Bind(R.id.comment_count)
            TextView commentCount;
            @Bind(R.id.follow_button)
            ToggleButton followButton;
            @Bind(R.id.more_text)
            TextView moreImagesText;

            public ViewHolder(View view) {
                ButterKnife.bind(this, view);
            }
        }
    }
}
